package thread;

public class BlockingQueue_ {
    private volatile int size;
    private String[] data = new String[10];
    private volatile int head;
    private volatile int tail;
    public synchronized void put(String elem) throws InterruptedException {
        while (size == data.length){
            this.wait();
        }
        data[tail] = elem;
        tail++;
        if(tail == data.length){
            tail = 0;
        }
        size++;
        this.notify();  // 用来唤醒 take 的阻塞
    }

    public synchronized String take() throws InterruptedException {
        while (size == 0){
            this.wait();
        }
        String temp = data[head];
        head++;
        if (head == data.length){
            head = 0;
        }
        size--;
        this.notify();  // 用来唤醒 put 的阻塞
        return temp;
    }

    public static void main(String[] args) {
        BlockingQueue_ bq = new BlockingQueue_();
        // 消费者
        Thread t1 = new Thread(()->{
            while (true) {
                try {
                    String s = bq.take();
                    System.out.println("消费元素" + s);
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        // 生产者
        Thread t2 = new Thread(()->{
            int num = 1;
            while (true) {
                try {
                    bq.put(num + "");
                    System.out.println("生产元素" + num++);
                    //Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();
    }
}
